package com.wanhong.springboot.ssm.framework.handler;


import com.wanhong.springboot.ssm.framework.common.Result;
import com.wanhong.springboot.ssm.framework.exception.BizException;
import com.wanhong.springboot.ssm.framework.exception.BizExceptionCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @author w_yu
 * @date 2020/11/26 14:52
 * @description: 全局异常捕获
 **/
@ResponseBody
@ControllerAdvice(basePackages = {"com.wanhong.springboot.ssm.service.controller"})
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BizException.class)
    public Result baseExceptionHandler(BizException ex) {
        log.debug("BizException:", ex);
        return new Result(ex.getCode(), null, ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result otherExceptionHandler(Exception ex) {
        log.error("Exception:", ex);
        return new Result(BizExceptionCodeEnum.SYSTEM_EXCEPTION_ERROR.getCode(), null, ex.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException ex) {
        log.warn("MethodArgumentNotValidException:", ex);
        StringBuilder errorMessage = new StringBuilder();
        BindingResult bindingResult = ex.getBindingResult();

        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage.append("[").append(fieldError.getDefaultMessage()).append("],");
        }
        String msg = "";
        if (errorMessage.toString() != null && !"".equals(errorMessage.toString())) {
            msg = errorMessage.substring(0, errorMessage.length() - 1);
        }

        return new Result(BizExceptionCodeEnum.REST_METHOD_ARGUMENT_NOT_VALID_ERROR.getCode(), null, msg);
    }
}